package com.base.springboot.starter.mybatisplus.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.springboot.starter.mybatisplus.util.StringUtil;

import java.util.*;

/**
 * 查询参数
 *
 * @author admin
 * @date 2020/5/19 AM10:15
 */
public class Query<T> extends LinkedHashMap<String, Object> {
	private static final long serialVersionUID = 1L;
	public static final String QUERY_ORDER_ASC = "ASC";
	public static final String QUERY_ORDER_DESC = "DESC";

    protected static final List<String> QUERY_LIST = new ArrayList<> ();
    /**
     * 第几页
     */
	public static final String QUERY_PAGE = "page";
    /**
     * 每页数量
     */
	public static final  String QUERY_LIMIT = "limit";
    /**
     * 排序字段
     */
	public static final String QUERY_SIDX = "sidx";
    /**
     * 排序类型
     */
	public static final String QUERY_ORDER = "order";

	static{
		QUERY_LIST.add(Query.QUERY_PAGE);
		QUERY_LIST.add(Query.QUERY_LIMIT);
		QUERY_LIST.add(Query.QUERY_SIDX);
		QUERY_LIST.add(Query.QUERY_ORDER);
	}
	
    /**
     * mybatis-plus分页参数
     */
    private Page<T> page;
    /**
     * 当前页码
     */
    private int currPage = 1;
    /**
     * 每页条数
     */
    private int limit = 10;

    public Query(Map<String, Object> params){
        this.putAll(params);

        //分页参数
        if(params.get(Query.QUERY_PAGE) != null){
            currPage = StringUtil.nullToInteger(params.get(Query.QUERY_PAGE));
        }
        if(params.get(Query.QUERY_LIMIT) != null){
            limit = StringUtil.nullToInteger(params.get(Query.QUERY_LIMIT));
        }

        this.put("offset", (currPage - 1) * limit);

        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        if(params.get(Query.QUERY_SIDX) != null){
            SqlFilter.sqlInject(StringUtil.null2Str(params.get(Query.QUERY_SIDX)));
        }
        if(params.get(Query.QUERY_ORDER) != null){
            SqlFilter.sqlInject(StringUtil.null2Str(params.get(Query.QUERY_ORDER)));
        }
        //mybatis-plus分页
        this.page = new Page<>(currPage, limit);

    }

    public IPage<T> getPage() {
        return page;
    }

    public int getCurrPage() {
        return currPage;
    }

    public int getLimit() {
        return limit;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }
        Query<?> query = (Query<?>) o;
        return currPage == query.currPage &&
                limit == query.limit &&
                Objects.equals(page, query.page);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), page, currPage, limit);
    }
}
